import React, { PureComponent } from 'react'
import {
  Radio, Tooltip, DatePicker, Select, message,
} from 'antd'
import { connect, history } from '@umijs/max'
import moment from 'moment'
import _ from 'lodash'
import HufuEchartsLine from '@/components/Echarts/line'
import { ProTable } from '@/components'
import styles from './index.less'

const { Option } = Select
const dateFormat = 'YYYY-MM-DD';
const currentDate = moment().format(dateFormat)

const execptionLineOptionsTemp = {
  grid: {
    top: '10%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    name: '',
    data: [],
  },
  yAxis: {
    name: '',
  },
  series: [
    {
      data: [],
    },
  ],
}

const lineData = {
  grid: {
    left: '3%',
    right: '2%',
    top: '12%',
    // bottom: '3%',
    containLabel: true,
  },
  legend: {
    data: ['昨天', '今天', '历史平均'],
    right: 0,
    top: 0,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['0:00', '1:00', '2:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
  },
  yAxis: {
    type: 'value',
  },
  series: [
    {
      name: '昨天',
      type: 'line',
      data: []
    },
    {
      name: '今天',
      type: 'line',
      data: [],
    },
    {
      name: '历史平均',
      type: 'line',
      data: [],
    },
  ],
}

const taskStatusFn = (taskStatus) => {
  let html = ''
  switch (taskStatus) {
    case 1:
      html = <><i className="iconfont icon-weiyunhang hu-blue" /> 未运行</>
      break;
    case 2:
      html = <><i className="iconfont icon-yunhangzhong_1 hu-blue" /> 运行中</>
      break;
    case 3:
      html = <><i className="iconfont icon-chenggong hu-green" /> 成功</>
      break;
    case 4:
      html = <><i className="iconfont icon-shibai1 hu-red" /> 失败</>
      break;
    case 5:
      html = <><i className="iconfont icon-weiyunhang hu-gray" /> 停止</>
      break;
    case 6:
      html = <><i className="iconfont icon-shibai1 hu-red" /> 部分失败</>
      break;
    case 7:
      html = <><i className="iconfont icon-yunhangzhong_1 hu-gray" /> 等待中</>
      break;
    case 8:
      html = <><i className="iconfont icon-weiyunhang hu-gray" /> 自动打断</>
      break;
  }
  return html
}

@connect(({ operation }) => ({ ...operation }))
class General extends PureComponent {
  state = {
    lineOption: execptionLineOptionsTemp,
    todayTask: lineData,
    monitorDays: 'weekRecord',
    failQuery: {
      timeType: 0,
    },
    runQuery: {
      runDate: currentDate,
    },
    errorQuery: {
      timeCase: 1
    },
    columns1: [
      {
        title: '任务名称',
        // dataIndex: 'taskName',
        key: 'taskName',
        width: '40%',
        render: (record) => (
          <span className={styles.link} onClick={() => { this.queryGetParentType(record?.nodeId, record?.taskName) }}>{record?.taskName}</span>
        ),
      },
      {
        title: '最近运行时间',
        dataIndex: 'lastRunningDate',
        key: 'lastRunningDate',
        width: '40%',
        render: (lastRunningDate) => (lastRunningDate || '-'),
      },
      {
        title: '失败总数',
        dataIndex: 'failedNum',
        key: 'failedNum',
        width: '20%',
        render: (failedNum) => (failedNum || '-'),
      },
    ],
    columns2: [
      {
        title: '任务名称',
        // dataIndex: 'taskName',
        key: 'taskName',
        width: '20%',
        render: (record) => (
          <span className={styles.link} onClick={() => { this.queryGetParentType(record?.nodeId, record?.taskName) }}>{record?.taskName}</span>
        ),
      },
      {
        title: '最近运行时间',
        dataIndex: 'lastRunningDate',
        key: 'lastRunningDate',
        width: '28%',
        render: (lastRunningDate) => (lastRunningDate || '-'),
      },
      {
        title: '执行时长(S)',
        dataIndex: 'runningTime',
        key: 'runningTime',
        width: '26%',
        render: (runningTime) => (runningTime || '-'),
      },
      {
        title: '状态',
        dataIndex: 'taskStatus',
        key: 'taskStatus',
        width: '26%',
        render: (taskStatus) => (taskStatusFn(taskStatus)),
      },
    ],
    columns3: [
      {
        title: '任务名称',
        key: 'taskName',
        width: '28%',
        render: (record) => (
          <span className={styles.link} onClick={() => { this.linkTo('3', '', record?.taskName) }}>{record?.taskName}</span>
        ),
      },
      {
        title: '状态',
        dataIndex: 'taskStatus',
        key: 'taskStatus',
        width: '20%',
        render: (taskStatus) => (taskStatusFn(taskStatus)),
      },
      {
        title: '开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: '26%',
        render: (startTime) => (startTime || '-'),
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
        width: '26%',
        render: (endTime) => (endTime || '-'),
      },

      // {
      //   title: '操作',
      //   key: 'number',
      //   width: '10%',
      //   render: (system) => (
      //     <>
      //       <span>查看</span>
      //       <span>忽略</span>
      //     </>
      //   ),
      // },
    ],
  }

  componentDidMount() {
    this.queryToday()
    this.querySummary()
    this.queryTaskMonitorList()
  }

  querySummary = () => {
    this.props.dispatch({
      type: 'operation/querySummary',
      cb: (res) => {
        const {
          successNum, failedNum, publishNum, unPublishNum, allTask
        } = res || {}
        this.setState({
          successNum,
          failedNum,
          publishNum,
          unPublishNum,
          allTask
        })
      },
    })
  }

  // 今日任务完成情况
  queryToday = () => {
    this.props.dispatch({
      type: 'operation/queryToday',
      cb: (res) => {
        const { historyAverageRecord, todayRecord, yesterdayRecord } = res || {}
        const { todayTask } = this.state
        const copyTodayTask = _.cloneDeep(todayTask)
        // 此处与后端约定，返回全部的值，缺少的值，用0代替
        copyTodayTask.series[0].data = yesterdayRecord?.map(item => item?.count)
        copyTodayTask.series[1].data = todayRecord?.map(item => item?.count)
        copyTodayTask.series[2].data = historyAverageRecord?.map(item => item?.count)
        this.setState({
          todayTask: copyTodayTask
        })
      },
    })
  }

  // 任务监控异常情况
  queryTaskMonitorList = () => {
    const { monitorDays, lineOption } = this.state
    this.props.dispatch({
      type: 'operation/queryTaskMonitorList',
      params: {
        // endDate: moment().format('YYYY-MM-DD'),
        // startDate: moment(
        //   Date.now() - 86400 * 1000 * (monitorDays - 1),
        // ).format('YYYY-MM-DD'),
      },
      cb: (res) => {
        const dataList = res[monitorDays]
        const timeArr = []
        const countArr = []
        dataList?.forEach(item => {
          timeArr.push(item.time)
          countArr.push(item.count)
        })
        const copyLineOption = _.cloneDeep(lineOption)
        copyLineOption.xAxis.data = timeArr
        copyLineOption.series = [
          {
            data: countArr,
          },
        ]
        this.setState({
          lineOption: copyLineOption,
        })
      },
    })
  }

  handleLineTabs = (e) => {
    this.setState({
      monitorDays: e.target.value,
    }, () => {
      this.queryTaskMonitorList()
    })
  }

  handleFailTask = (e) => {
    this.setState({
      failQuery: {
        timeType: e.target.value,
      }
    })
  }

  handleDatePicker = (date, dateString) => {
    this.setState({
      runQuery: {
        runDate: dateString,
      }
    })
  }

  handleErrorSelect = (val) => {
    this.setState({
      errorQuery: {
        timeCase: val,
      },
    })
  }

  linkTo = (step, filterValue, value = '') => {
    const { onTabsChange } = this.props
    value ? this.handleSearchDefault(value) : this.handleFilterValue(filterValue)
    onTabsChange(step)
  }

  handleFilterValue = (val) => {
    let params = []
    if (typeof val === 'string') {
      const valArr = val.split(',')
      valArr.forEach(item => params.push(Number(item)))
    } else {
      params = [val]
    }
    this.props.dispatch({
      type: 'operation/saveFilterValue',
      params: {
        filteredDefaultValue: params
      },
    })
  }

  handleSearchDefault = (val) => {
    this.props.dispatch({
      type: 'operation/saveSearchDefault',
      params: {
        defaultNodeName: val
      },
    })
  }

  queryGetParentType = (nodeId, nodeName) => {
    this.props.dispatch({
      type: 'operation/queryGetParentType',
      params: {
        nodeId,
      },
      cb: (res) => {
        const { msg, status, data } = res
        if (status === 200) {
          if (data === 1) {
            // 作业开发
            history.push(`/data-development/offline/script-development?nodeId=${nodeId}&nodeName=${nodeName}`)
          } else {
            history.push(`/data-development/offline/workflow-development?nodeId=${nodeId}&nodeName=${nodeName}`)
          }
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  render() {
    const { todayTask, lineOption, successNum, failedNum, publishNum, unPublishNum, failQuery, runQuery, errorQuery, allTask, columns1, columns2, columns3 } = this.state
    return (
      <div className={styles.general}>
        <div className={styles.page_content_title}>
          <div className={styles.title_item} onClick={() => { this.linkTo('2', 1) }}>
            <p>已发布</p>
            <p><span className={styles.num}>{publishNum}</span>/ <span>{allTask}</span></p>
            <div className={styles.iconfont_box}>
              <i className="iconfont-colour2 icon-yunhangzhong" />
            </div>
          </div>
          <div className={styles.title_item} onClick={() => { this.linkTo('2', 0) }}>
            <p>未发布</p>
            <p><span className={styles.num}>{unPublishNum}</span>/ <span>{allTask}</span></p>
            <div className={styles.iconfont_box}>
              <i className="iconfont-colour2 icon-chenggong_1" />
            </div>
          </div>
          <div className={styles.title_item} onClick={() => { this.linkTo('3', '4,6') }}>
            <p>失败数 <Tooltip placement="topLeft" title="所有失败（失败、部分失败）的任务，并且未处理的数量"><i className="iconfont icon-yiwentishi" /></Tooltip></p>
            <p><span className={styles.num}>{failedNum}</span></p>
            <div className={styles.iconfont_box}>
              <i className="iconfont-colour2 icon-shibai_1" />
            </div>
          </div>
          <div className={styles.title_item} onClick={() => { this.linkTo('3', 3) }}>
            <p>成功数 <Tooltip placement="topLeft" title="所有运行成功的任务记录数量"><i className="iconfont icon-yiwentishi" /></Tooltip></p>
            <p className={styles.sign}>{successNum}</p>
            <div className={styles.iconfont_box}>
              <i className="iconfont-colour2 icon-tingzhi_1" />
            </div>
          </div>
        </div>
        <div className={styles.first_floor}>
          <div className={styles.left}>
            <div className={styles.column}>
              今日任务完成情况
            </div>
            <div className={styles.charts_box}>
              <HufuEchartsLine
                options={todayTask}
              />
            </div>
          </div>
          <div className={styles.center}>
            <div className={styles.column}>
              失败任务TOP10
              <Radio.Group defaultValue={0} size="small" onChange={this.handleFailTask}>
                <Radio.Button value={3}>昨天</Radio.Button>
                <Radio.Button value={0}>近3天</Radio.Button>
                <Radio.Button value={1}>近7天</Radio.Button>
                <Radio.Button value={2}>近30天</Radio.Button>
              </Radio.Group>
            </div>
            <div className={styles.table_cont}>
              <ProTable
                method="get"
                url="/api/v1/offlineDev/operation/v2/failedTask/top"
                rowKey={({ nodeId, lastRunningDate }) => (`${nodeId}_${lastRunningDate}`)}
                pageSize={10}
                columns={columns1}
                showQuickJumper={false}
                showSizeChanger={false}
                query={failQuery}
                pagination={null}
                scroll={{ x: true, y: 220 }}
              />
            </div>
          </div>
          <div className={styles.right}>
            <div className={styles.column}>
              <span>运行时长TOP10 <Tooltip placement="topLeft" title="对当天运行任务执行时间进行排行TOP10，可自定义选择具体某一日期进行查看任务运行时长情况"><i className="iconfont icon-yiwentishi" /> </Tooltip></span>
              <DatePicker defaultValue={moment(currentDate, dateFormat)} format={dateFormat} onChange={this.handleDatePicker} />
            </div>
            <div className={styles.table_cont}>
              <ProTable
                method="get"
                url="/api/v1/offlineDev/operation/v2/runningTime/top"
                rowKey={({ nodeId, lastRunningDate }) => (`${nodeId}_${lastRunningDate}`)}
                pageSize={10}
                columns={columns2}
                showQuickJumper={false}
                showSizeChanger={false}
                query={runQuery}
                pagination={null}
                scroll={{ x: true, y: 220 }}
              />
            </div>
          </div>
        </div>
        <div className={styles.second_floor}>
          <div className={styles.left}>
            <div className={styles.column}>
              任务监控异常情况
              <Radio.Group defaultValue="weekRecord" size="small" onChange={this.handleLineTabs}>
                <Radio.Button value="weekRecord">近7天</Radio.Button>
                <Radio.Button value="monthRecord">近30天</Radio.Button>
              </Radio.Group>
            </div>
            <div className={styles.charts_box2}>
              <HufuEchartsLine
                options={lineOption}
              />
            </div>
          </div>
          <div className={styles.right}>
            <div className={styles.column}>
              <span>异常任务监控 <Tooltip placement="topLeft" title="监控任务运行失败的记录，并且未处理过的任务记录。"><i className="iconfont icon-yiwentishi" /> </Tooltip></span>
              <Select style={{ width: 100 }} defaultValue={1} onChange={this.handleErrorSelect}>
                <Option key={4} value={4}>昨天</Option>
                <Option key={1} value={1}>3天</Option>
                <Option key={2} value={2}>7天</Option>
                <Option key={3} value={3}>30天</Option>
              </Select>
            </div>
            <div className={styles.table_cont}>
              <ProTable
                method="get"
                url="/api/v1/offlineDev/operation/v2/taskMonitor/error"
                query={errorQuery}
                rowKey={({ nodeId, endTime }) => (`${nodeId}_${endTime}`)}
                pageSize={10}
                columns={columns3}
                showQuickJumper={false}
                showSizeChanger={false}
                scroll={{ x: true, y: 220 }}
              />
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default General
